//
//  PersonTools.m
//  BaseTools
//
//  Created by 李挺哲 on 15/12/30.
//  Copyright © 2015年 ltz. All rights reserved.
//

#import "PersonTools.h"
#import "IdCard.h"
static PersonTools * personTools;
@interface PersonTools (){
    
}

@property (nonatomic, strong) NSString * storeName;

@end

@implementation PersonTools
+ (instancetype)shareInstanceWithStoreName:(NSString *)storeName {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        personTools = [[self alloc] init];
        personTools.storeName = storeName;
    });
    
    
    
    
    return personTools;
}

-(NSPersistentStoreCoordinator *)psc{
    
    if (_psc) {
        return _psc;
    }
    
    
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
    // 添加持久化存储库，这里使用SQLite作为存储库
    NSError *error = nil;
    _psc=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model] ;
    NSPersistentStore *store = [_psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if (store == nil) { // 直接抛异常
        [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
    }
    
    return _psc;
    
}
-(NSManagedObjectModel *)model{
    
    if (!_model) {
        _model = [NSManagedObjectModel mergedModelFromBundles:nil];
    }
    
    return _model;
}

-(NSManagedObjectContext *)context{
    
    if (!_context) {
        _context = [[NSManagedObjectContext alloc] init];
        _context.persistentStoreCoordinator = self.psc;
    }
    return  _context;
    
}

/**
 *  添加一个 Person
 *
 *  @param person <#person description#>
 */
-(void)saveWithPerson:(Person *)person{
    
    NSError *error = nil;
    // 传入上下文，创建一个Person实体对象
    NSManagedObject *personObject = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    // 设置Person的简单属性
//    NSArray *nameArr = @[@"gogoing",@"duang",@"uzi",@"omg"];
//    
//    NSString *name = [NSString stringWithFormat:@"%@%d",nameArr[arc4random_uniform(4)],arc4random_uniform(200)];
    [personObject setValue:person.name forKey:@"name"];
    [personObject setValue:[[NSNumber alloc] initWithInt:person.age.intValue] forKey:@"age"];
    // 传入上下文，创建一个Card实体对象
    NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:self.context];
    [card setValue:person.card.no forKey:@"no"];
    // 设置Person和Card之间的关联关系
    [personObject setValue:card forKey:@"card"];
    // 利用上下文对象，将数据同步到持久化存储库
    
    BOOL success = [_context save:&error];
    if (!success) {
        [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
    }
    
    
}



-(BOOL)deletePerson:(Person *)person{
    
    // 初始化一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    // 设置要查询的实体
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", person.name];
    request.predicate = predicate;
    //    // 执行请求
    
    NSError * error=nil;
    NSArray *objs = [self.context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    // 遍历数据
    for (NSManagedObject *obj in objs) {
       
        
        
        // 传入需要删除的实体对象
        [_context deleteObject:obj];
        // 将结果同步到数据库
        NSError *error = nil;
        [_context save:&error];
        if (error) {
            [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
            return NO;
        }
        else{
            return YES;
        
        }
    }
    
    
    
    return NO;
    
   



}
/**
 *  获取所有的Person对象
 *
 *  @return <#return value description#>
 */
-(NSMutableArray *)persons{
    NSMutableArray *persons = [NSMutableArray array];
    
    
    // 初始化一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    // 设置要查询的实体
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"];
    //    request.predicate = predicate;
    //    // 执行请求
    
    NSError * error=nil;
    NSArray *objs = [self.context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    // 遍历数据
    for (NSManagedObject *obj in objs) {
        
        Person * p=[[Person alloc] init];
        NSLog(@"name=%@", [obj valueForKey:@"name"]);
        p.name=[obj valueForKey:@"name"];
        NSLog(@"age =%@",[obj valueForKey:@"age"]);
        p.age=[obj valueForKey:@"age"];
        NSManagedObject *card = [obj valueForKey:@"card"];
        NSLog(@"IDcard =%@",[card valueForKey:@"no"]);
        IdCard *idCard=     [[IdCard alloc] init];
        idCard.no=[card valueForKey:@"no"];
        p.card=idCard;
        [persons addObject:p];

    }
    
    
    
    
    return persons;
    
    
}



-(NSMutableArray *)getSearchPersons:(NSString *)text{
    NSMutableArray *persons = [NSMutableArray array];
    
    
    // 初始化一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    // 设置要查询的实体
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
   NSString *string= [NSString stringWithFormat:@"*%@*",text];
    
    NSLog(@"string  %@",string);
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", string];
        request.predicate = predicate;
    //    // 执行请求
    
    NSError * error=nil;
    NSArray *objs = [self.context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    // 遍历数据
    for (NSManagedObject *obj in objs) {
        
        Person * p=[[Person alloc] init];
        NSLog(@"name=%@", [obj valueForKey:@"name"]);
        p.name=[obj valueForKey:@"name"];
        NSLog(@"age =%@",[obj valueForKey:@"age"]);
        p.age=[obj valueForKey:@"age"];
        NSManagedObject *card = [obj valueForKey:@"card"];
        NSLog(@"IDcard =%@",[card valueForKey:@"no"]);
        IdCard *idCard=     [[IdCard alloc] init];
        idCard.no=[card valueForKey:@"no"];
        p.card=idCard;
        [persons addObject:p];
        
    }
    
    
    
    
    return persons;
    
    
}

@end
